/*
 * @Author: qiang.yan yanqiang@happycfc.com
 * @Date: 2024-01-10 16:32:08
 * @LastEditTime: 2024-01-10 17:42:24
 * @LastEditors: qiang.yan yanqiang@happycfc.com
 * @Description: 描述
 */
import React from 'react'
import classNames from 'classnames'
import { usePropsValue } from '../../hooks/use-props-value'
import { withNativeProps } from '../../utils/native-props'
import { warn, error } from '@/library/tool-kits/log'
import { useRadioGroup } from './group-context'
import { NativeInput } from '../CheckBox/native-input'
import { CheckIcon } from '../CheckBox/check-icon'
import type { RadioProps } from './type'

const classPrefix = 'rt-radio'

export const Radio: React.FC<RadioProps> = (props) => {
  const context = useRadioGroup()

  const {
    block = false,
    checked,
    defaultChecked = false,
    icon,
    id,
    onClick,
    onChange,
    value,
    children,
  } = props

  let { disabled = false } = props

  let [actChecked, setActChecked] = usePropsValue<boolean>({
    value: checked,
    defaultValue: defaultChecked,
    onChange,
  })

  if (context && (value === undefined || value === null)) {
    error(
      'Radio',
      'When used within `Radio.Group`, the `value` prop of `Radio` will not be Undefined or Null.',
    )
    return null
  }

  if (context && value !== undefined) {
    if (checked !== undefined) {
      warn(
        'Radio',
        'When used within `Radio.Group`, the `checked` prop of `Radio` will not work.',
      )
    }
    if (defaultChecked) {
      warn(
        'Radio',
        'When used within `Radio.Group`, the `defaultChecked` prop of `Radio` will not work.',
      )
    }

    actChecked = context.value.includes(value)
    setActChecked = function (innerChecked: boolean) {
      if (innerChecked) {
        context.check(value)
      } else {
        context.uncheck(value)
      }
      onChange?.(innerChecked)
    } as any

    disabled = disabled || context.disabled
  }

  const renderIcon = () => {
    if (icon) {
      return (
        <div className={`${classPrefix}-custom-icon`}>
          {icon(actChecked)}
        </div>
      )
    }

    return (
      <div className={`${classPrefix}-icon`}>{actChecked && <CheckIcon />}</div>
    )
  }

  return withNativeProps(
    props,
    // eslint-disable-next-line jsx-a11y/label-has-associated-control, jsx-a11y/no-noninteractive-element-interactions
    <label
      onClick={onClick}
      className={classNames(classPrefix, {
        [`${classPrefix}-checked`]: actChecked,
        [`${classPrefix}-disabled`]: disabled,
        [`${classPrefix}-block`]: block,
      })}
    >
      <NativeInput
        type="radio"
        checked={actChecked}
        onChange={setActChecked}
        disabled={disabled}
        id={id}
      />
      {renderIcon()}
      {children && (
        <div className={`${classPrefix}-content`}>{children}</div>
      )}
    </label>,
  )
}
